package com.yuanhua.xcxmng.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Month;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.yuanhua.xcxmng.wechat.cache.LocalCache;
import com.yuanhua.xcxmng.wechat.entity.Item;
import com.yuanhua.xcxmng.wechat.entity.Report;
import com.yuanhua.xcxmng.wechat.entity.UserRun;
import com.yuanhua.xcxmng.wechat.entity.UserTarget;
import com.yuanhua.xcxmng.wechat.service.MyService;
import com.yuanhua.xcxmng.wechat.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wechat/report")
public class ReportController extends BaseController {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private MyService   myService;

    @GetMapping("tabs")
    public String tabs(String threeSession) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];
        Date now = new Date();
        int month = DateUtil.month(now);
        List<Integer> list = Lists.newArrayList();
        list.add(DateUtil.offsetMonth(now, -5).month() + 1);
        list.add(DateUtil.offsetMonth(now, -4).month() + 1);
        list.add(DateUtil.offsetMonth(now, -3).month() + 1);
        list.add(DateUtil.offsetMonth(now, -2).month() + 1);
        list.add(DateUtil.offsetMonth(now, -1).month() + 1);
        list.add(month + 1);
        return JsonUtils.toJson(list);
    }

    public static void main(String[] args) {
        System.out.println("2018-03-10 23:12:12".substring(5, 10));
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("userStepsInfo")
    public String userStepsInfo(String threeSession, int index) throws Exception {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        Date current = new Date();
        List<Date> list = Lists.newArrayList();
        list.add(DateUtil.offsetMonth(current, -5));
        list.add(DateUtil.offsetMonth(current, -4));
        list.add(DateUtil.offsetMonth(current, -3));
        list.add(DateUtil.offsetMonth(current, -2));
        list.add(DateUtil.offsetMonth(current, -1));
        list.add(current);
        Date now = list.get(index);
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];
        DateTime startOfWeek = DateUtil.beginOfWeek(now);
        DateTime endOfWeek = DateUtil.endOfWeek(now);
        DateTime startOfMonth = DateUtil.beginOfMonth(now);
        DateTime endOfMonth = DateUtil.endOfMonth(now);
        List<UserRun> userRunWeeks = myService.findRunDataByOpenIdDate(openId, startOfWeek, endOfWeek);
        List<UserRun> userRunMonths = myService.findRunDataByOpenIdDate(openId, startOfMonth, endOfMonth);
        List<String> weeks = Lists.newArrayList();
        List<String> months = Lists.newArrayList();
        DateTime next = DateUtil.offsetDay(startOfWeek, -1);
        while (true) {
            next = DateUtil.offsetDay(next, 1);
            if (next.isBeforeOrEquals(endOfWeek)) {
                weeks.add(next.toDateStr());
            } else {
                break;
            }
        }

        next = DateUtil.offsetDay(startOfMonth, -1);
        while (true) {
            next = DateUtil.offsetDay(next, 1);
            //            if(DateUtil.dayOfWeek(next)!=2){
            if (next.isBeforeOrEquals(endOfMonth) && next.isBeforeOrEquals(new Date())) {
                months.add(next.toDateStr());
            } else {
                break;
            }
            //            }
        }

        List<Long> weekRuns = Lists.newArrayList();
        List<Long> monthRuns = Lists.newArrayList();
        for (String date : weeks) {
            boolean isfind = false;
            for (UserRun userRun : userRunWeeks) {
                if (DateUtil.formatDate(userRun.getGmtDate()).equals(date)) {
                    isfind = true;
                    weekRuns.add(userRun.getStep());
                    break;
                }
            }
            if (!isfind) {
                weekRuns.add(0L);
            }
        }
        for (String date : months) {
            boolean isFind = false;
            for (UserRun userRun : userRunMonths) {
                if (DateUtil.formatDate(userRun.getGmtDate()).equals(date)) {
                    isFind = true;
                    monthRuns.add(userRun.getStep());
                    break;
                }
            }
            if (!isFind) {
                monthRuns.add(0L);
            }
        }

        UserTarget userTarget = myService.findTargetByOpenId(openId);
        Long target = userTarget == null ? 0 : userTarget.getTargetStep();
        List<Long> targetList = Lists.newArrayList();
        List<Report> result = Lists.newArrayList();
        weekRuns.stream().forEach(x -> targetList.add(target));
        Report report = new Report();
        report.setCategories(weeks.stream().map(x -> x = x.substring(5, 10)).collect(Collectors.toList()));
        report.setData(weekRuns);
        report.setTarget(targetList);
        result.add(report);
        List<Long> targetList1 = Lists.newArrayList();
        Report report1 = new Report();
        report1.setCategories(months.stream().map(x -> x = x.substring(5, 10)).collect(Collectors.toList()));
        report1.setData(monthRuns);
        monthRuns.stream().forEach(x -> targetList1.add(target));
        report1.setTarget(targetList1);
        result.add(report1);
        return JsonUtils.toJson(result);
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("tableItems")
    public String tableItems(String threeSession, int index) throws Exception {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];
        Date current = new Date();
        List<Date> list = Lists.newArrayList();
        list.add(DateUtil.offsetMonth(current, -5));
        list.add(DateUtil.offsetMonth(current, -4));
        list.add(DateUtil.offsetMonth(current, -3));
        list.add(DateUtil.offsetMonth(current, -2));
        list.add(DateUtil.offsetMonth(current, -1));
        list.add(current);
        Date now = list.get(index);
        DateTime startOfMonth = DateUtil.beginOfMonth(now);
        DateTime endOfMonth = DateUtil.endOfMonth(now);
        List<UserRun> userRunMonths = myService.findRunDataByOpenIdDate(openId, startOfMonth, endOfMonth);
        UserTarget userTarget = myService.findTargetByOpenId(openId);
        List<String> months = Lists.newArrayList();
        DateTime next = DateUtil.offsetDay(startOfMonth, -1);
        while (true) {
            next = DateUtil.offsetDay(next, 1);
            if (next.isBeforeOrEquals(endOfMonth)) {
                months.add(next.toDateStr());
            } else {
                break;
            }
        }

        List<Item> monthRuns = Lists.newArrayList();
        for (String date : months) {
            for (UserRun userRun : userRunMonths) {
                if (DateUtil.formatDate(userRun.getGmtDate()).equals(date)) {
                    Item item = new Item();
                    item.setId(userRun.getId());
                    item.setDate(date);
                    item.setTarget(userTarget == null ? 0 : userTarget.getTargetStep());
                    item.setStep(userRun.getStep());
                    item.setCurrency(userRun.getCurrency());
                    monthRuns.add(item);
                }
            }
        }
        Collections.reverse(monthRuns);
        return JsonUtils.toJson(monthRuns);
    }
}
